<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-3-26
 * Time: 上午10:16
 */

namespace common\models;


use common\components\tools\FileHelper;
use common\components\tools\ImgCompress;

/**
 * Class ImageIndex
 * @package common\models
 *
 * @property-read string|null $imageFilePath
 */
class ImageIndex extends \common\models\base\ImageIndex
{
    const TYPE_DEFAULT = 10;
    const TYPE_ICBC_IMAGE = 11;

    /**
     * @param $url
     * @param $dir_pre
     * @return ImageIndex|null|static
     */
    public static function imageModelGet($url, $dir_pre)
    {
        if (is_dir(\Yii::getAlias($dir_pre))){}else{
            FileHelper::createDirectory(\Yii::getAlias($dir_pre));
        }
        $m = self::findOne(['image_url' => $url, 'target_dir_pre' => $dir_pre]);
        if (!$m){
            $y = time().rand(1000, 9999).".".FileHelper::getExtensionName1($url);
            $x = file_get_contents($url);
            $z = \Yii::getAlias($dir_pre)."/".$y;
            file_put_contents($z, $x);
//            ImgCompress::dowork($z, $z);
            FileHelper::resizeImage($z, $z);
            $m = new self();
            $m->image_url = $url;
            $m->target_path = $y;
            $m->target_dir_pre = $dir_pre;
            $m->created_at = time();
            $m->updated_at = time();
            $m->type = self::TYPE_ICBC_IMAGE;
            $m->save();
        }else{
            if (!file_exists($m->imageFilePath)){
                $y = time().rand(1000, 9999).".".FileHelper::getExtensionName1($url);
                $x = file_get_contents($url);
                $z = \Yii::getAlias($dir_pre)."/".$y;
                file_put_contents($z, $x);
                FileHelper::resizeImage($z, $z);
                $m->image_url = $url;
                $m->target_path = $y;
                $m->target_dir_pre = $dir_pre;
            }
            $m->updated_at =time();
            $m->save();
        }
        return $m;
    }

    /**
     * @return bool|string
     */
    public function getImageFilePath()
    {
        return \Yii::getAlias($this->target_dir_pre.DIRECTORY_SEPARATOR.$this->target_path);
    }
}